import { onUnmounted } from "vue";

export function G_throttle(fun: Function, delay: number) {
  let init = true,
    timer: any = null;
  return function (...args: any) {
    if (init) {
      init = false;
      fun(args);
    } else {
      if (timer) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        fun(args);
      }, delay);
    }
  };
}

export function G_getSquareDom(dom: HTMLElement) {
  const obs = new ResizeObserver(
    G_throttle(() => {
      if (!dom.parentElement) return;
      const { clientHeight: height, clientWidth: width } = dom.parentElement;
      const size = Math.min(height, width);
      dom.style.height = dom.style.width = `${size}px`;
    }, 100)
  );
  obs.observe(dom);
  onUnmounted(() => {
    obs.disconnect();
  });
}
